<?php
declare (strict_types = 1);

namespace app\common\service;

use app\common\logic\SeckillLogic;
use think\facade\Db;

class SeckillService extends BaseService
{
    protected $seckillLogic;

    public function __construct()
    {
        parent::__construct();
        $this->seckillLogic = new SeckillLogic();
    }

    /**
     * 获取秒杀商品列表
     * @param array $params
     * @return array
     */
    public function getSeckillList($params = [])
    {
        $where = [];
        $where[] = ['status', '=', 1];
        
        // 只显示进行中的秒杀
        $now = time();
        $where[] = ['stime', '<=', $now];
        $where[] = ['etime', '>=', $now];
        
        if (!empty($params['sid'])) {
            $where[] = ['sid', '=', $params['sid']];
        }
        
        $list = $this->seckillLogic->getSeckillList($where);
        return [
            'status' => true,
            'msg' => '获取成功',
            'data' => $list
        ];
    }

    /**
     * 获取秒杀商品详情
     * @param int $id 秒杀商品ID
     * @return array
     */
    public function getSeckillDetail($id)
    {
        if (empty($id)) {
            return [
                'status' => false,
                'msg' => '参数错误',
                'data' => []
            ];
        }
        
        $detail = $this->seckillLogic->getSeckillDetail($id);
        return [
            'status' => true,
            'msg' => '获取成功',
            'data' => $detail
        ];
    }

    /**
     * 秒杀下单
     * @param int $seckill_id 秒杀商品ID
     * @param int $user_id 用户ID
     * @param int $num 购买数量
     * @return array
     */
    public function createSeckillOrder($seckill_id, $user_id, $num = 1)
    {
        if (empty($seckill_id) || empty($user_id) || $num <= 0) {
            return [
                'status' => false,
                'msg' => '参数错误',
                'data' => []
            ];
        }

        Db::startTrans();
        
        // 验证秒杀活动
        $check_result = $this->seckillLogic->checkSeckillStatus($seckill_id);
        if (!$check_result['status']) {
            Db::rollback();
            return $check_result;
        }
        
        // 验证购买限制
        $limit_result = $this->seckillLogic->checkPurchaseLimit($seckill_id, $user_id);
        if (!$limit_result['status']) {
            Db::rollback();
            return $limit_result;
        }
        
        // 创建秒杀订单
        $create_result = $this->seckillLogic->createOrder($check_result['data'], $user_id, $num);
        if (!$create_result['status']) {
            Db::rollback();
            return $create_result;
        }
        
        Db::commit();
        return [
            'status' => true,
            'msg' => '下单成功',
            'data' => $create_result['data']
        ];
    }
}